package org.hepeng.workx.jdbc;

import org.hepeng.workx.extension.XPoint;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author he peng
 */

@XPoint("randomReadAndWrite")
public interface SelectDataSourceStrategy {

    DataSource chooseDataSource(Object key);

    default List<DataSourceMetadata> getAllDataSources() {
        return DataSourceMetadataStore.getAllDataSourceMetaDatas();
    }

    default List<DataSource> getReadOnlyDataSources() {
        List<DataSource> readModeDataSources = new ArrayList<>();
        for (DataSourceMetadata dataSourceMetaData : getAllDataSources()) {
            if (Objects.equals(DataSourceMetadata.DataSourceOpsMode.READ_ONLY , dataSourceMetaData.getMode())) {
                readModeDataSources.add(dataSourceMetaData.getDataSource());
            }
        }
        return Collections.unmodifiableList(readModeDataSources);
    }

    default List<DataSource> getWriteOnlyDataSources() {
        List<DataSource> writeModeDataSources = new ArrayList<>();
        for (DataSourceMetadata dataSourceMetaData : getAllDataSources()) {
            if (Objects.equals(DataSourceMetadata.DataSourceOpsMode.WRITE_ONLY , dataSourceMetaData.getMode())) {
                writeModeDataSources.add(dataSourceMetaData.getDataSource());
            }
        }
        return Collections.unmodifiableList(writeModeDataSources);
    }

    default List<DataSource> getReadAndWriteDataSources() {
        List<DataSource> readAndWriteModeDataSources = new ArrayList<>();
        for (DataSourceMetadata dataSourceMetaData : getAllDataSources()) {
            if (Objects.equals(DataSourceMetadata.DataSourceOpsMode.READ_AND_WRITE , dataSourceMetaData.getMode())) {
                readAndWriteModeDataSources.add(dataSourceMetaData.getDataSource());
            }
        }
        return Collections.unmodifiableList(readAndWriteModeDataSources);
    }
}
